package com.xxx.yuedong.campaign.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.xxx.yuedong.campaign.db.dao.TeamDao;
import com.xxx.yuedong.campaign.pojo.Team;
import com.xxx.yuedong.campaign.service.TeamService;
import com.xxx.yuedong.common.exception.YuedongException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author HG
 * @version 1.0
 **/
@Slf4j
@Service
public class TeamServiceImpl implements TeamService {
    @Autowired
    private TeamDao teamDao;

    @Override
    public int insert(Team team) {
        int rows = teamDao.insert(team);
        return rows;
    }

    @Override
    public int addTeamById(Long id) {
        HashMap team = teamDao.searchTeamById(id);
        String member = (String) team.get("members");
        ArrayList memberArray = JSONUtil.parse(member).toBean(ArrayList.class);

        for (Object m : memberArray) {
            if(m.toString().equals(StpUtil.getLoginIdAsString())) {
                log.error("异常消息用户{}：【MySQL数据库异常无法新增数据】",id);
                throw  new YuedongException(HttpStatus.SC_NO_CONTENT,"已加入该跑团");
            }
        }

        memberArray.add(StpUtil.getLoginIdAsLong());

        HashMap param = new HashMap();
        param.put("id", id);
        param.put("members", memberArray.toString());
        int rows = teamDao.addTeamById(param);
        return rows;
    }

    @Override
    public ArrayList<HashMap> searchAllTeam() {
        ArrayList<HashMap> teamList = teamDao.searchAllTeam();
        return teamList;
    }
}
